﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.SessionState;
using YULI.Web.UI;
using YULI.Common;

namespace YULI.Web.tools
{
    /// <summary>
    /// 管理员AJAX请求处理
    /// </summary>
    public class admin_ajax : IHttpHandler, IRequiresSessionState
    {
        Model.sys_config sysConfig = new BLL.sys_config().loadConfig();//系统配置信息

        public void ProcessRequest(HttpContext context)
        {
            //取得处事类型
            string action = YULIRequest.GetQueryString("action");
            if (action != "admin_login")
            {
                //检查管理员是否登录
                if (!new ManagePage().IsAdminLogin())
                {
                    context.Response.Write("{\"status\": 0, \"msg\": \"尚未登录或已超时，请登录后操作！\"}");
                    return;
                }
            }
            
            switch (action)
            {
                case "manager_validate": //验证管理员用户名是否重复
                    manager_validate(context);
                    break;
                case "admin_login": //管理员登录
                    admin_login(context);
                    break;
                case "edit_nav": //编辑后台导航
                    edit_nav(context);
                    break;
                case "get_admin_data": //获取管理员信息列表
                    get_admin_data(context);
                    break;
                case "edit_admin_status": //编辑管理员帐号状态
                    edit_admin_status(context);
                    break;
            }
        }

        #region 验证管理员用户名是否重复========================
        private void manager_validate(HttpContext context)
        {
            string user_name = YULIRequest.GetString("param");
            if (string.IsNullOrEmpty(user_name))
            {
                context.Response.Write("{ \"info\":\"请输入用户名\", \"status\":\"n\" }");
                return;
            }
            BLL.manager bll = new BLL.manager();
            if (bll.Exists(user_name))
            {
                context.Response.Write("{ \"info\":\"用户名已被占用，请更换！\", \"status\":\"n\" }");
                return;
            }
            context.Response.Write("{ \"info\":\"用户名可使用\", \"status\":\"y\" }");
            return;
        }
        #endregion

        #region 验证管理员登录后台OK============================
        private void admin_login(HttpContext context)
        {
            string username = YULIRequest.GetString("txtUserName");
            string password = YULIRequest.GetString("txtPassword");
            string code = YULIRequest.GetString("txtCode");

            //检验
            if (string.IsNullOrEmpty(username))
            {
                context.Response.Write("{ \"info\":\"用户名不可为空\", \"status\":\"0\" }");
                return;
            }
            if (string.IsNullOrEmpty(password))
            {
                context.Response.Write("{ \"info\":\"密码不可为空\", \"status\":\"0\" }");
                return;
            }
            if (string.IsNullOrEmpty(code))
            {
                context.Response.Write("{ \"info\":\"验证码不可为空\", \"status\":\"0\" }");
                return;
            }
            if (context.Session[YULIKeys.SESSION_CODE] == null)
            {
                context.Response.Write("{ \"info\":\"系统找不到验证码\", \"status\":\"0\" }");
                return;
            }
            if (code.ToLower() != context.Session[YULIKeys.SESSION_CODE].ToString().ToLower())
            {
                context.Response.Write("{ \"info\":\"验证码输入不正确\", \"status\":\"0\" }");
                return;
            }

            if (context.Session["AdminLoginSun"] == null)
            {
                context.Session["AdminLoginSun"] = 1;
            }
            else
            {
                context.Session["AdminLoginSun"] = Convert.ToInt32(context.Session["AdminLoginSun"]) + 1;
            }
            //判断登录错误次数
            if (context.Session["AdminLoginSun"] != null && Convert.ToInt32(context.Session["AdminLoginSun"]) > 5)
            {
                context.Response.Write("{ \"info\":\"错误超过5次，关闭浏览器重新登录！\", \"status\":\"0\" }");
                return;
            }

            BLL.manager bll = new BLL.manager();
            Model.manager model = bll.GetModel(username, password, true);
            if (model == null)
            {
                context.Response.Write("{ \"info\":\"用户名或密码有误，请重试！\", \"status\":\"0\" }");
                return;
            }
            context.Session[YULIKeys.SESSION_ADMIN_INFO] = model;
            context.Session.Timeout = 45;
            //写入登录日志
            if (sysConfig.logstatus > 0)
            {
                new BLL.manager_log().Add(model.id, model.user_name, YULIEnums.ActionEnum.Login.ToString(), "用户登录");
            }
            //写入Cookies
            Utils.WriteCookie("YULIRememberName", model.user_name, 14400);
            Utils.WriteCookie("AdminName", sysConfig.sysencryptstring, model.user_name);
            Utils.WriteCookie("AdminPwd", sysConfig.sysencryptstring, model.password);


            context.Response.Write("{ \"info\":\"登录成功！\", \"status\":\"1\", \"url\":\"/admin/index.aspx\" }");
            return;
        }
        #endregion

        #region 编辑后台导航OK============================
        private void edit_nav(HttpContext context)
        {
            string nav_id = YULIRequest.GetString("hidNavID");
            string nav_parent_id = YULIRequest.GetString("selCategory");
            string nav_title = YULIRequest.GetString("txtTitle");
            string call_index = YULIRequest.GetString("txtCallIndex");
            string icon_url = YULIRequest.GetString("txtIconUrl");
            string link_url = YULIRequest.GetString("txtLinkUrl");
            string sort_id = YULIRequest.GetString("txtSortID");
            string is_lock = YULIRequest.GetString("rdoIsShow");
            string remark = YULIRequest.GetString("txtRemark");

            //检验
            if (string.IsNullOrEmpty(nav_parent_id))
            {
                context.Response.Write("{ \"info\":\"请选择上级导航\", \"status\":\"0\" }");
                return;
            }
            if (string.IsNullOrEmpty(nav_title))
            {
                context.Response.Write("{ \"info\":\"请填写栏目名称\", \"status\":\"0\" }");
                return;
            }
            if (string.IsNullOrEmpty(call_index))
            {
                context.Response.Write("{ \"info\":\"请填写调用别名\", \"status\":\"0\" }");
                return;
            }
            if (Convert.ToInt32(nav_parent_id) > 0)
            {
                if (string.IsNullOrEmpty(link_url))
                {
                    context.Response.Write("{ \"info\":\"请填写链接地址\", \"status\":\"0\" }");
                    return;
                }
            }

            if (string.IsNullOrEmpty(sort_id))
            {
                sort_id = "99";
            }
            if (string.IsNullOrEmpty(is_lock))
            {
                is_lock = "0";
            }
            if (string.IsNullOrEmpty(icon_url) && Convert.ToInt32(nav_parent_id) != 0)
            {
                icon_url = "fa-angle-double-right";
            }

            //获取所选上级导航ID的父ID
            int parent_parent_id = new BLL.navigation().GetNavParentId(Convert.ToInt32(nav_parent_id));
            if (parent_parent_id > 0)
            {
                context.Response.Write("{ \"info\":\"导航只支持二级菜单\", \"status\":\"0\" }");
                return;
            }

            Model.navigation model = new Model.navigation();
            BLL.navigation bll = new BLL.navigation();

            try
            {
                if (string.IsNullOrEmpty(nav_id) || nav_id == "0")  //ID为空，则是添加操作
                {
                    model.nav_type = YULIEnums.NavigationEnum.Admin.ToString();
                    model.name = call_index;
                    model.title = nav_title;
                    model.sub_title = nav_title;
                    model.icon_url = icon_url;
                    model.link_url = link_url;
                    model.sort_id = int.Parse(sort_id);
                    model.is_lock = int.Parse(is_lock);
                    model.remark = remark;
                    model.parent_id = int.Parse(nav_parent_id);
                    model.channel_id = 1;

                    if (bll.Add(model) <= 0)
                    {
                        context.Response.Write("{ \"info\":\"添加后台导航失败，请重试！\", \"status\":\"0\" }");
                        return;
                    }
                    new Web.UI.ManagePage().AddAdminLog(YULIEnums.ActionEnum.Add.ToString(), "添加导航菜单:" + model.title); //记录日志
                }
                else if (Convert.ToInt32(nav_id) > 0)  //ID不为空，则是修改操作
                {
                    model = bll.GetModel(Convert.ToInt32(nav_id));

                    model.nav_type = YULIEnums.NavigationEnum.Admin.ToString();
                    model.name = call_index;
                    model.title = nav_title;
                    model.sub_title = nav_title;
                    model.icon_url = icon_url;
                    model.link_url = link_url;
                    model.sort_id = int.Parse(sort_id);
                    model.is_lock = int.Parse(is_lock);
                    model.remark = remark;

                    //如果选择的父ID不是自己,则更改
                    if (int.Parse(nav_parent_id) != model.id)
                    {
                        model.parent_id = int.Parse(nav_parent_id);
                    }

                    if (!bll.Update(model))
                    {
                        context.Response.Write("{ \"info\":\"修改后台导航失败，请重试！\", \"status\":\"0\" }");
                        return;
                    }
                    new Web.UI.ManagePage().AddAdminLog(YULIEnums.ActionEnum.Edit.ToString(), "修改导航菜单:" + model.title); //记录日志
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("{ \"info\":\"" + ex.Message + "\", \"status\":\"0\" }");
                return;
            }

            context.Response.Write("{ \"info\":\"编辑导航菜单成功！\", \"status\":\"1\", \"url\":\"/admin/settings/nav_config.aspx\" }");
            return;
        }
        #endregion

        #region 获取管理员信息列表==============================
        private void get_admin_data(HttpContext context)
        {
            Model.manager adminModel = new ManagePage().GetAdminInfo();//获得当前登录管理员信息
            if (adminModel == null)
            {
                return;
            }
            Model.manager_role roleModel = new BLL.manager_role().GetModel(adminModel.role_id);//获得管理角色信息
            if (roleModel == null)
            {
                return;
            }

            int pageSize = 10;
            int page = 1;
            string strWhere = string.Empty;
            string orderBy = "";
            int totalCount = 0;

            DataTable dt = new BLL.manager().GetList(pageSize, page, strWhere, orderBy, out totalCount).Tables[0];

            string DataInfo = string.Empty;
            if (dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    string id = dt.Rows[i]["id"].ToString();
                    string user_name = dt.Rows[i]["user_name"].ToString();
                    string real_name = dt.Rows[i]["real_name"].ToString();
                    string role_id = dt.Rows[i]["role_id"].ToString();
                    string telephone = dt.Rows[i]["telephone"].ToString();
                    string email = dt.Rows[i]["email"].ToString();
                    string add_time = dt.Rows[i]["add_time"].ToString();
                    string is_lock = dt.Rows[i]["is_lock"].ToString();
                }
            }

        }
        #endregion

        #region 编辑管理员帐号状态OK============================
        private void edit_admin_status(HttpContext context)
        {
            int admin_id = YULIRequest.GetInt("AdminID", 0);
            int status_id_now = YULIRequest.GetInt("StatusID", -1);

            //检验
            if (admin_id<=0)
            {
                context.Response.Write("{ \"info\":\"管理员ID参数有误\", \"status\":\"0\" }");
                return;
            }
            if (admin_id < 0)
            {
                context.Response.Write("{ \"info\":\"管理员帐号当前状态参数有误\", \"status\":\"0\" }");
                return;
            }
            
            try
            {
                BLL.manager bll = new BLL.manager();
                Model.manager model = bll.GetModel(admin_id);

                int status_id = 0;
                if (status_id_now == 1)
                {
                    status_id = 0;
                }
                else if (status_id_now == 0)
                {
                    status_id = 1;
                }
                bool is_ok = bll.UpdateField(admin_id, "is_lock=" + status_id + "");
                if (!is_ok)
                {
                    context.Response.Write("{ \"info\":\"操作失败，请重试！\", \"status\":\"0\" }");
                    return;
                }
            }
            catch (Exception ex)
            {
                context.Response.Write("{ \"info\":\"" + ex.Message + "\", \"status\":\"0\" }");
                return;
            }

            context.Response.Write("{ \"info\":\"修改管理员帐号状态成功！\", \"status\":\"1\", \"url\":\"/admin/manager/manager_list.aspx\" }");
            return;
        }
        #endregion

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}